package com.tengju.support.application.message;

import com.google.common.collect.Lists;
import com.tengju.support.application.shared.ApplicationException;
import com.tengju.support.application.shared.ApplicationExceptionCode;
import com.tengju.support.domain.model.message.*;
import com.tengju.support.domain.model.user.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class MessageBatchPushRelationService {

    private final MessageRepository messageRepository;
    private final MessageTaskRepository messageTaskRepository;

    @Transactional(value = "dealerTransactionManager", rollbackFor = Exception.class)
    public List<Message> generateBatch(MessageTask messageContent, List<UserInfo> userInfos, MessageChannel sendType) {

        TaskId messageId = messageContent.getTaskId();
        SendStatus beforeStatus = messageContent.getSendStatus();
        SendStatus afterStatus;
        //站内信 并且不需要app推送 状态直接置为已发送
        if (MessageChannel.STATION_LETTER == sendType) {
            afterStatus = SendStatus.SEND;
        } else {
            afterStatus = SendStatus.SENDING;
        }

        messageContent.changeSendStatus(afterStatus);
        //变更发送状态
        boolean result = messageTaskRepository.updateSendStatus(messageId, beforeStatus, messageContent.getSendStatus());
        if (!result) {
            throw ApplicationException.error(ApplicationExceptionCode.SEND_STATUS_CHANGE_FAIL,messageId.getValue());
        }

        List<List<UserInfo>> partition = Lists.partition(userInfos, 10);
        List<Message> messageBatchRelationList = new ArrayList<>();
        //生成批次
        for (List<UserInfo> userInfoBatch : partition) {
            BatchId batchId = new BatchId(messageId, messageContent.getMessageType(), UUID.randomUUID().toString());
            List<Message> messageBatchRelation = MessageFactory.create(
                    messageContent,
                    batchId,
                    userInfoBatch,
                    afterStatus
            );
            messageBatchRelationList.addAll(messageBatchRelation);
        }
        messageRepository.batchSave(messageBatchRelationList);

        return messageBatchRelationList;
    }


}
